package clue

import (
	"context"
	"git.mycaigou.com/gfyx/common/simplecopier"
	"git.mycaigou.com/gfyx/common/usermetadata"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/oppty/report"
	contract2 "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/repository/business_opportunity"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/utils/ossfile"
	micro_gfyx_user_service "git.mycaigou.com/gfyx/micro-gfyx-api/proto/micro_gfyx_user_service_proto/micro-gfyx-user-service"
	"git.myscrm.cn/golang/stark/v4"
)

type ReportFollowService struct {
	reportFollowRepository contract2.ReportFollowRepositoryIface
}

func NewReportFollowService(reportFollowRepository contract2.ReportFollowRepositoryIface) ReportFollowServiceIface {
	return &ReportFollowService{
		reportFollowRepository: reportFollowRepository,
	}
}

func (r *ReportFollowService) SaveFollowRecord(ctx context.Context, request *report.SaveFollowRecordRequest) error {
	resp, err := r.reportFollowRepository.SaveFollowRecord(ctx, request)
	if err != nil {
		return err
	}
	if request.FollowStatus == 1 || request.FollowStatus == 2 || request.FollowStatus == 3 {
		// 如果报备来源是SHARE，则需要调用公共服务，同步用户提交的最新跟进状态
		if resp != nil && resp.GetIsSuccess() == true && resp.GetReportSourceType() == "SHARE" && resp.GetReportSourceId() != "" {

			userInfo := usermetadata.GetUserInfo(ctx)
			updateData := &micro_gfyx_user_service.ReportFromSharing{}
			updateData.ReportStatusCode = request.FollowStatus
			if request.FollowStatus == 2 {
				updateData.ReportStatus = "已签约"
			} else if request.FollowStatus == 3 {
				updateData.ReportStatus = "未签约"
			} else if request.FollowStatus == 1 {
				updateData.ReportStatus = "跟进中"
			}
			_, err := r.reportFollowRepository.UpdateReportShare(ctx, userInfo.CommonUserDataUid, resp.GetReportSourceId(), updateData)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func (r *ReportFollowService) GetFollowRecordList(ctx context.Context, reportId string, page int32, pageSize int32) ([]map[string]interface{}, int64, error) {
	list := make([]map[string]interface{}, 0)
	followRecord, err := r.reportFollowRepository.GetFollowRecordList(ctx, reportId, page, pageSize)
	if err != nil {
		return list, 0, err
	}

	if followRecord != nil && followRecord.GetList() != nil {
		for _, item := range followRecord.GetList() {
			// 获取oss的图片链接
			if item.Images != nil {
				for index, image := range item.Images {
					imageUrl, err := ossfile.GetSignURL(image)
					if err != nil {
						stark.Logger.Errorf(ctx, "ossfile.GetSignURL err: %s", err)
					} else {
						item.Images[index] = imageUrl
					}
				}
			}
		}
		list, _ := simplecopier.SliceStructToSliceMapByJsonTag(followRecord.GetList())
		return list, followRecord.GetTotal(), nil
	}
	return list, 0, nil
}
